package com.webex.ta.hydra.hamal;

import com.webex.ta.hydra.hamal.iface.Hamal;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Cisco WebEx.
 * User: vegaz
 * Date: 2010-9-6
 * Time: 14:03:29
 */
public class Connections {
    private Map<String, Hamal.Client> connections = new HashMap<String, Hamal.Client>();

    private static Connections instance;

    private Connections() {
    }

    public static Connections getInstance() {
        if (instance == null)
            instance = new Connections();
        return instance;
    }

    public void prepareConnection(String name, String host, int port) throws TTransportException {
        Hamal.Client client;
        if (connections.containsKey(name)) {
            client = connections.get(name);
            if (client.getInputProtocol().getTransport().isOpen()) {
                client.getInputProtocol().getTransport().close();
            }
        }

        TTransport tr = new TSocket(host, port);
        tr.open();
        TProtocol proto = new TBinaryProtocol(tr);
        client = new Hamal.Client(proto);
        connections.put(name, client);
    }

    public Hamal.Client getConnection(String name) {
        return connections.get(name);
    }
}
